<template>
  <div class="settings">
    <div class="settings-header">
      <h3>⚙️ 系统设置</h3>
      <p>配置应用程序的各种参数和偏好</p>
    </div>

    <div class="settings-content">
      <!-- AI设置 -->
      <div class="settings-section">
        <h4>🤖 AI对话设置</h4>
        <div class="settings-group">
          <div class="setting-item">
            <label>系统提示词</label>
            <textarea
              v-model="settings.aiSystemPrompt"
              placeholder="输入AI对话的系统提示词..."
              rows="4"
              @blur="saveSettings"
            ></textarea>
            <p class="setting-description">设置AI助手的角色和对话风格</p>
          </div>
          
          <div class="setting-item">
            <label>温度 (Temperature)</label>
            <div class="slider-container">
              <input
                type="range"
                v-model="settings.aiTemperature"
                min="0"
                max="1"
                step="0.1"
                @change="saveSettings"
              />
              <span class="slider-value">{{ settings.aiTemperature }}</span>
            </div>
            <p class="setting-description">控制AI回答的创造性 (0: 保守, 1: 创造性)</p>
          </div>

          <div class="setting-item">
            <label>最大回复长度</label>
            <input
              type="number"
              v-model="settings.aiMaxTokens"
              min="100"
              max="8000"
              step="100"
              @blur="saveSettings"
            />
            <p class="setting-description">设置AI回复的最大token数量</p>
          </div>
        </div>
      </div>

      <!-- 界面设置 -->
     <div class="settings-section">
       <h4>🎨 界面设置</h4>
       <div class="settings-group">
         <div class="setting-item">
           <label>配色方案</label>
           <select v-model="settings.colorScheme" @change="saveSettings">
             <option value="light">浅色主题</option>
             <option value="dark">深色主题</option>
             <option value="auto">跟随系统</option>
           </select>
         </div>

         <div class="setting-item">
           <label>3D分子显示模式</label>
           <select v-model="settings.moleculeDisplayMode" @change="saveSettings">
             <option value="ball">球体模式</option>
             <option value="stick">棍球模式</option>
           </select>
           <p class="setting-description">选择3D分子结构的显示方式</p>
         </div>

         <div class="setting-item">
           <label>晶体结构模式</label>
           <div class="checkbox-group">
             <label>
               <input type="checkbox" v-model="settings.crystalMode" @change="saveSettings" />
               显示晶体结构（多个晶胞）
             </label>
           </div>
           <p class="setting-description">启用后显示完整的晶体结构，包括多个重复单元</p>
         </div>

         <div class="setting-item" v-if="settings.crystalMode">
           <label>晶胞数量</label>
           <select v-model="settings.unitCells" @change="saveSettings">
             <option value="1">1x1x1</option>
             <option value="2">2x2x2</option>
             <option value="3">3x3x3</option>
             <option value="4">4x4x4</option>
             <option value="5">5x5x5</option>
           </select>
           <p class="setting-description">选择显示的晶胞重复单元数量</p>
         </div>

         <div class="setting-item">
           <label>语言设置</label>
           <select v-model="settings.language" @change="saveSettings">
             <option value="zh-CN">中文</option>
             <option value="en-US">English</option>
           </select>
         </div>

         <div class="setting-item">
           <label>动画效果</label>
           <div class="checkbox-group">
             <label>
               <input type="checkbox" v-model="settings.animations" @change="saveSettings" />
               启用动画效果
             </label>
           </div>
         </div>
       </div>
     </div>

      <!-- 数据设置 -->
      <div class="settings-section">
        <h4>💾 数据设置</h4>
        <div class="settings-group">
          <div class="setting-item">
            <label>自动保存</label>
            <div class="checkbox-group">
              <label>
                <input type="checkbox" v-model="settings.autoSave" @change="saveSettings" />
                启用自动保存
              </label>
            </div>
          </div>

          <div class="setting-item">
            <label>保存间隔 (分钟)</label>
            <input
              type="number"
              v-model="settings.autoSaveInterval"
              min="1"
              max="60"
              @blur="saveSettings"
            />
          </div>

          <div class="setting-item">
            <label>数据保留时间</label>
            <select v-model="settings.dataRetention" @change="saveSettings">
              <option value="7">7天</option>
              <option value="30">30天</option>
              <option value="90">90天</option>
              <option value="365">1年</option>
              <option value="forever">永久保留</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="settings-actions">
        <button class="action-btn primary" @click="saveSettings">
          💾 保存设置
        </button>
        <button class="action-btn secondary" @click="resetSettings">
          🔄 重置为默认
        </button>
        <button class="action-btn danger" @click="exportSettings">
          📤 导出设置
        </button>
      </div>
    </div>

    <!-- 状态提示 -->
    <div v-if="statusMessage" :class="['status-message', statusType]">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const settings = ref({
  // AI设置
  aiSystemPrompt: '你是一个专业的材料科学助手，帮助用户分析分子结构和材料性质。请提供准确、专业的回答.',
  aiTemperature: 0.7,
  aiMaxTokens: 1000,
  
  // 界面设置
  colorScheme: 'light',
  moleculeDisplayMode: 'ball', // 'ball' 或 'stick'
  crystalMode: false, // 是否显示晶体结构
  unitCells: 1, // 显示的晶胞数量
  language: 'zh-CN',
  animations: true,
  
  // 数据设置
  autoSave: true,
  autoSaveInterval: 5,
  dataRetention: '30'
})

const statusMessage = ref('')
const statusType = ref('info')

const showStatus = (message, type = 'info') => {
  statusMessage.value = message
  statusType.value = type
  setTimeout(() => {
    statusMessage.value = ''
  }, 3000)
}

const saveSettings = () => {
  try {
    localStorage.setItem('appSettings', JSON.stringify(settings.value))
    showStatus('设置已保存', 'success')
    
    // 应用设置
    applySettings()
    
    // 触发自定义事件通知其他组件设置已更改
    const settingsChangeEvent = new CustomEvent('appSettingsChanged', {
      detail: { settings: settings.value }
    })
    window.dispatchEvent(settingsChangeEvent)
  } catch (error) {
    console.error('保存设置失败:', error)
    showStatus('保存失败', 'error')
  }
}

const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('appSettings')
    if (savedSettings) {
      settings.value = { ...settings.value, ...JSON.parse(savedSettings) }
    }
    applySettings()
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

const resetSettings = () => {
  if (confirm('确定要重置所有设置为默认值吗？')) {
    settings.value = {
      aiSystemPrompt: '你是一个专业的材料科学助手，帮助用户分析分子结构和材料性质。请提供准确、专业的回答.',
      aiTemperature: 0.7,
      aiMaxTokens: 8000,
      colorScheme: 'light',
      moleculeDisplayMode: 'ball',
      crystalMode: false,
      unitCells: 1,
      language: 'zh-CN',
      animations: true,
      autoSave: true,
      autoSaveInterval: 5,
      dataRetention: '30'
    }
    saveSettings()
    showStatus('设置已重置为默认值', 'success')
  }
}

const exportSettings = () => {
  try {
    const jsonData = JSON.stringify(settings.value, null, 2)
    const blob = new Blob([jsonData], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `molecule-scope-settings-${new Date().getTime()}.json`
    link.click()
    
    URL.revokeObjectURL(url)
    showStatus('设置导出成功', 'success')
  } catch (error) {
    console.error('导出设置失败:', error)
    showStatus('导出失败', 'error')
  }
}

const applySettings = () => {
  // 应用配色方案
  if (settings.value.colorScheme === 'dark') {
    document.documentElement.setAttribute('data-theme', 'dark')
  } else if (settings.value.colorScheme === 'light') {
    document.documentElement.setAttribute('data-theme', 'light')
  } else {
    // 跟随系统
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light')
  }
  
  // 应用语言设置
  document.documentElement.lang = settings.value.language
}

// 初始化加载设置
onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.settings {
  height: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  overflow-y: auto;
}

.settings-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.settings-header h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.settings-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.settings-content {
  width: 100%;
  margin: 0 auto;
}

.settings-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.settings-section h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.settings-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.setting-item label {
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.setting-item input,
.setting-item select,
.setting-item textarea {
  padding: 10px 12px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  font-family: inherit;
}

.setting-item input:focus,
.setting-item select:focus,
.setting-item textarea:focus {
  border-color: #007bff;
  outline: none;
}

.setting-item textarea {
  resize: vertical;
  min-height: 80px;
}

.setting-description {
  font-size: 12px;
  color: #6c757d;
  margin: 4px 0 0 0;
}

.slider-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.slider-container input[type="range"] {
  flex: 1;
  height: 6px;
  background: #ddd;
  border-radius: 3px;
  outline: none;
  -webkit-appearance: none;
}

.slider-container input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  background: #007bff;
  border-radius: 50%;
  cursor: pointer;
}

.slider-value {
  min-width: 30px;
  text-align: center;
  font-weight: 500;
  color: #495057;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: normal;
  cursor: pointer;
}

.checkbox-group input[type="checkbox"] {
  width: 16px;
  height: 16px;
}

.settings-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

.action-btn {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background: #007bff;
  color: white;
}

.action-btn.primary:hover {
  background: #0056b3;
}

.action-btn.secondary {
  background: #6c757d;
  color: white;
}

.action-btn.secondary:hover {
  background: #545b62;
}

.action-btn.danger {
  background: #dc3545;
  color: white;
}

.action-btn.danger:hover {
  background: #c82333;
}

.status-message {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  z-index: 1000;
}

.status-message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

@media (max-width: 768px) {
  .settings-actions {
    flex-direction: column;
  }
  
  .settings-section {
    padding: 15px;
  }
}
</style>